package forkJoin;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class SumTask extends RecursiveTask<Long> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3553083516598289568L;
	
	static final int THRESHOLD = 100;
    long[] array;
    int start;
    int end;

    SumTask(long[] array, int start, int end) {
    this.array = array;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        if (end - start <= THRESHOLD) {
            // 如果任务足够小,直接计算:
            long sum = 0;
            for (int i = start; i < end; i++) {
                sum += array[i];
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            System.out.println(String.format("compute %d~%d = %d", start, end, sum));
            return sum;
        }
        
        System.out.println("Thread is : "+Thread.currentThread().getName()+"----------"+Thread.currentThread().getId());
        
        // 任务太大,一分为二:
        int middle = (end + start) / 2;
        System.out.println(String.format("split %d~%d ==> %d~%d, %d~%d", start, end, start, middle, middle, end));
        SumTask subtask1 = new SumTask(this.array, start, middle);
        SumTask subtask2 = new SumTask(this.array, middle, end);
        invokeAll(subtask1, subtask2);
        Long subresult1 = subtask1.join();
        Long subresult2 = subtask2.join();
        Long result = subresult1 + subresult2;
        System.out.println("result = " + subresult1 + " + " + subresult2 + " ==> " + result);
        return result;
    }
    
    public static void main(String[] args) {
    	// 创建随机数组成的数组:
        long[] array = new long[400];
        fillRandom(array);
        long sum = 0l;
        long startTime1 = System.currentTimeMillis();
        for (int i = 0; i < array.length; i++) {
			//long l = array[i];
			sum += array[i] ;
		}
        long startTime2 = System.currentTimeMillis();
        System.out.println(" sum : "+sum + (startTime2-startTime1)+" :ms.");
        // fork/join task:
        ForkJoinPool fjp = new ForkJoinPool(4); // 最大并发数4
        ForkJoinTask<Long> task = new SumTask(array, 0, array.length);
        long startTime = System.currentTimeMillis();
        //关键代码是fjp.invoke(task)来提交一个Fork/Join任务并发执行，然后获得异步执行的结果。
        Long result = fjp.invoke(task);
        long endTime = System.currentTimeMillis();
        System.out.println("Fork/join sum: " + result + " in " + (endTime - startTime) + " ms.");
        System.out.println("Thread is : "+Thread.currentThread().getName()+"----------"+Thread.currentThread().getId());

	}

	private static void fillRandom(long[] array2) {
		// TODO Auto-generated method stub
		for (int i = 0; i < array2.length; i++) {
			array2[i] = 1 ;
		}
	}
}
